import axios from "axios";
import encryption from "./encryption";
import { Loading } from "element-ui";
import { MessageBox } from "element-ui";
import { Message } from "element-ui";
import router from "_my/router/index";

import _ from "lodash";
const http = axios.create({
  timeout: 40000, //超时时长
});
const options = {
  background: "rgba(0,0,0,0)",
  lock: true,
  target: "body",
};
//loading对象
let loading;
//当前正在请求的数量
let needLoadingRequestCount = 0;

//显示loading
function showLoading(text) {
  options.text = text || "正在加载";
  // 后面这个判断很重要，因为关闭时加了抖动，此时loading对象可能还存在，
  // 但needLoadingRequestCount已经变成0.避免这种情况下会重新创建个loading
  if (needLoadingRequestCount === 0 && !loading) {
    loading = Loading.service(options);
    loading.$el.style.display = "block";
    loading.$el.children[0].children[0].style.marginTop = "10px";
    loading.$el.children[0].children[1].style.color = "#fff";
    loading.$el.children[0].children[0].children[0].style.stroke = "#fff";
    loading.$el.children[0].style.width = "140px";
    loading.$el.children[0].style.height = "75px";
    loading.$el.children[0].style.borderRadius = "5px";
    loading.$el.children[0].style.background = "rgba(0, 0, 0, .7)";
    loading.$el.children[0].style.left = "calc(50% - 70px)";
    {
    }
  }
  needLoadingRequestCount++;
}

//隐藏loading
function hideLoading() {
  needLoadingRequestCount--;
  needLoadingRequestCount = Math.max(needLoadingRequestCount, 0); //做个保护
  if (needLoadingRequestCount === 0) {
    //关闭loading
    toHideLoading();
  }
}

//防抖：将 300ms 间隔内的关闭 loading 便合并为一次。防止连续请求时， loading闪烁的问题。
var toHideLoading = _.debounce(() => {
  if (loading) {
    loading.close();
    loading = null;
  }
}, 300);
//添加请求拦截器

http.interceptors.request.use(
  (config) => {
    const obj = encryption(config.data);
    config.data = obj.arr;
    config.headers.encryption = obj.status || true;
    config.headers.token = `Bearer ${sessionStorage.getItem("token")}`;
    //判断当前请求是否设置了不显示Loading
    if (config.showLoading !== false) {
      showLoading(config.loadingText);
    }
    return config;
  },
  (err) => {
    //判断当前请求是否设置了不显示Loading
    if (config.showLoading !== false) {
      hideLoading();
    }
    Message.error("请求超时!");
    return Promise.resolve(err);
  }
);

//响应拦截器
http.interceptors.response.use(
  (response) => {
    delete response.headers;
    delete response.request;
    //判断当前请求是否设置了不显示Loading（不显示自然无需隐藏）
    if (response.config.showLoading !== false) {
      hideLoading();
      delete response.config;
    }
    if (response.data.code === 502) {
      MessageBox.alert(
        `<div style='display:flex' > <span style='font-size:24px;color:red;margin-right:10px' class='el-icon-warning-outline'></span><span>${response.data.message}</span></div>`,
        "错误",
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: "确定",
        }
      );
    }
    if (response.data.code === 202) {
      Message.error(response.data.message);
      if (response.data.message === "token已失效,请重新登录！") {
        setTimeout(() => {
          sessionStorage.clear();
          router.push("/");
          location.reload();
        }, 1000);
      }
    }
    if (response.data.code === 201) {
      Message.success(response.data.message);
    }
    return response;
  },
  (error) => {
    //判断当前请求是否设置了不显示Loading（不显示自然无需隐藏）
    if (error.config.showLoading !== false) {
      hideLoading();
    }
    MessageBox.alert(
      `<div style='display:flex' > <span style='font-size:24px;color:red;margin-right:10px' class='el-icon-warning-outline'></span><span>http请求通讯错误！${error.message}</span></div>`,
      "错误",
      {
        dangerouslyUseHTMLString: true,
        confirmButtonText: "确定",
      }
    );
    return Promise.reject(error);
  }
);

export default http;
